<template>
  <div class="app-container">
    <div>

      <el-button type="primary" plain @click="showChuanyueDialog">传阅文件审批</el-button>
    </div>
    <!-- {{list}} -->
    <div style="padding: 10px" />
    <el-table
      v-loading="listLoading"
      :data="list"
      style="width: 100%"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="状态" align="center" width="100px">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.sta==0 && scope.row.chexiao==0" type="warning">审核</el-tag>
          <el-tag v-if="scope.row.sta==1 && scope.row.chexiao==0" type="success">通过</el-tag>
          <el-tag v-if="scope.row.sta==2 && scope.row.chexiao==0" type="danger">拒绝</el-tag>
          <el-tag v-if="scope.row.chexiao==1" type="info">撤销</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="申请编号" align="center" width="100px">
        <template slot-scope="scope">
          <el-tag> {{ scope.row.id }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="申请时间" align="center" width="110px">
        <template slot-scope="scope">
          {{ getFormatedTimeStr(scope.row.createTime) }}
        </template>
      </el-table-column>

      <!-- <el-table-column label="名称" align="center">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column> -->

      <el-table-column label="编号" align="center">
        <template slot-scope="scope">
          {{ scope.row.bianhao }}
        </template>
      </el-table-column>

      <el-table-column label="来文单位" align="center">
        <template slot-scope="scope">
          {{ scope.row.danwei }}
        </template>
      </el-table-column>

      <el-table-column label="文号" align="center">
        <template slot-scope="scope">
          {{ scope.row.wenhao }}
        </template>
      </el-table-column>

      <el-table-column label="标题" align="center">
        <template slot-scope="scope">
          {{ scope.row.biaoti }}
        </template>
      </el-table-column>

      <el-table-column label="开始时间" align="center">
        <template slot-scope="scope">
          {{ getFormatedTimeStr(scope.row.shouwenDate) }}
        </template>
      </el-table-column>
      <el-table-column label="内容摘要" align="center">
        <template slot-scope="scope">
          {{ scope.row.zhaiyao }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="分发范围" align="center">
        <template slot-scope="scope">
          <span v-for="(item,index) in scope.row.readers" :key="index">
            {{ item.name }}、
          </span>
        </template>
      </el-table-column> -->

      <!--     <el-table-column label="相关图片" align="center">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.pics.length > 0"
            style="width: 48px; height: 48px"
            :src=" scope.row.pics[0]"
            :preview-src-list=" scope.row.pics"
          />

        </template>
      </el-table-column> -->

      <el-table-column label="相关附件" align="center">
        <template slot-scope="scope">
          <p v-for="(item,index) in scope.row.attaches " :key="index" style="">
            <el-link :href="item.path" type="primary" target="_blank">{{ item.name }}</el-link>
          </p>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="250px">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" plain @click="seeDetail(scope.row.id)">详情 </el-button>
          <el-button v-if="scope.row.sta>0 && scope.row.chexiao == 0" size="mini" type="primary" plain @click="printPdf(scope.row.id)">生成PDF </el-button>
          <el-button v-if="(scope.row.chexiao == 0)" size="mini" type="danger" plain @click="revertApply(scope.$index)">撤回 </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="padding: 10px" />
    <el-pagination
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageCount"
      layout="total, sizes, prev, pager, next, jumper"
      :total="dataTotal"
      @size-change="onPageSizeChange"
      @current-change="onCurrentPageChange"
    />

    <el-dialog
      :visible.sync="chuanyueDialog.visible"
      width="40%"
      :close-on-click-modal="false"
      top="5vh"
      center
      :show-close="false"
    >
      <div>
        <el-form ref="form" size="mini" label-position="left" label-width="100px">
          <el-row>
            <!-- 左侧 -->
            <el-col :span="11">
              <div class="title"><i class="el-icon-document" /> 申请单</div>

              <el-form-item label="收文单位">
                <el-input v-model="chuanyueDialog.danwei" />
              </el-form-item>

                <el-form-item label="文件类型">
                  <el-select v-model="chuanyueDialog.fileTag" placeholder="请选择" style="width: 100%;">
                    <el-option v-for="item in rangeArr" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>

              <el-form-item label="文号">
                <el-input v-model="chuanyueDialog.wenhao" />
              </el-form-item>

              <el-form-item label="标题">
                <el-input v-model="chuanyueDialog.biaoti" />
              </el-form-item>

              <el-form-item label="收文时间">
                <el-date-picker v-model="chuanyueDialog.shouwenDate" placeholder="选择日期" style="width: 100%;" />
              </el-form-item>

              <el-form-item label="内容摘要">
                <el-input v-model="chuanyueDialog.zhaiyao" type="textarea" :rows="4" placeholder="请输入内容" />
              </el-form-item>

              <el-form-item label="附件">
                <el-upload ref="attaches" :action="uploadconfig.url" :on-success="uploadAttachSuccess" multiple>
                  <el-button size="mini" type="primary" plain>点击上传附件</el-button>
                </el-upload>
              </el-form-item>

              <!-- <el-form-item label="分发范围">
                <el-cascader v-model="chuanyueDialog.readers" :options="userList" :props="props" clearable style="width: 100%;" />
              </el-form-item> -->
            </el-col>
            <!-- 右侧 -->
            <el-col :span="11" :offset="2">
              <div class="title"><i class="el-icon-s-check" /> 审核流程</div>
              <div v-for="(item,index) in chuanyueDialog.auditors" :key="index">
                <!-- 箭头：第一个不显示 -->
                <div v-if="index>0" class="step-arrow">
                  <el-row>
                    <el-col :span="8">
                      <div><i class="el-icon-caret-bottom" /></div>
                    </el-col>
                  </el-row>
                </div>
                <!-- 步骤样式 -->
                <div class="step">
                  <el-row>
                    <el-col :span="8">
                      <div class="step-info-left">{{ item.stepName || item.positionName }}</div>
                    </el-col>
                    <el-col :span="16">
                      <div class="step-info-right">{{ item.name }}</div>
                    </el-col>
                  </el-row>
                </div>
              </div>
            </el-col>
          </el-row>

        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="chuanyueDialog.visible = false">关 闭</el-button>
        <el-button type="primary" @click="clickApply()">提 交</el-button>
      </span>
    </el-dialog>

    <el-dialog title="" width="60%" :visible.sync="detailDialog.visible" top="5vh">
      <chuanyuewenjian-detail :id="detailDialog.id" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="(detailDialog.visible = false)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  Message
} from 'element-ui'

import {
  websock
} from '@/websock'
import moment from 'moment'
import {
  uploadconfig
} from '@/const'
import { quchongAuditors } from '@/utils/utils'
import ChuanyuewenjianDetail from '../../components/details/chuanyuewenjianDetail.vue'

export default {
  components: { ChuanyuewenjianDetail },
  filters: {
    statusFilter(sta) {
      const statusMap = {
        1: 'info',
        2: 'success',
        3: 'danger'
      }
      return statusMap[sta]
    }
  },
  data() {
    return {
      uploadconfig,
      props: { multiple: true },
      list: null,
      listLoading: true,
      pageIndex: 1,
      pageCount: 10,
      dataTotal: 0,
      userList: [],
      // 添加员工
      chuanyueDialog: {
        visible: false,
        bianhao: '',
        danwei: '',
        wenhao: '',
        biaoti: '',
        shouwenDate: '',
        zhaiyao: '',
        // readers: [],
        pics: [],
        attaches: [],
        auditors: [],
        fileTag: ""
      },
      rangeArr: [],
      detailDialog: {
        visible: false,
        id: 0
      }
    }
  },
  async created() {
    this.getList()
    this.fileTagListFun()

    const res = await websock.getContactList()
    console.log('created', res)
    const userList = []
    for (let i = 0; i !== res.length; i++) {
      userList.push({
        value: i + '',
        label: res[i].name,
        children: []
      })
      for (let j = 0; j !== res[i].userList.length; j++) {
        userList[i].children.push({
          value: JSON.stringify({
            uid: res[i].userList[j].uid,
            name: res[i].userList[j].name
          }),
          label: res[i].userList[j].name
        })
      }
    }
    this.userList = userList

    const auditors = await websock.getAuditors({ typ: 17 })
    console.log('auditors', auditors)
    quchongAuditors(auditors)
    this.chuanyueDialog.auditors = auditors
  },
  methods: {
    // 获取格式化时间字符串
    getFormatedTimeStr(stamp, str = 'MM-DD HH:mm') {
     	  return moment(stamp).format(str)
    },
    // 获取文件类型
    async fileTagListFun(){
      let data = await websock.fileTagList();
      if(data&&data.length) {
        this.rangeArr = data.map((v) => {
          return {
            value: v.id, label: v.name
          }
        });
        this.chuanyueDialog.fileTag = this.rangeArr[0].value
      }
    },
    getList() {
      this.listLoading = true
      websock.chuanyueWenjianRecordWeb({
        pageIndex: this.pageIndex,
        pageCount: this.pageCount
      }).then(
        (data) => {
          this.listLoading = false
          this.list = data.list
          this.dataTotal = data.count
        }
      )
    },
    uploadAttachSuccess(res, file) {
      console.log('upload attach success', res, file)
      if (res.code !== 0) {
        return Message({
          message: res.message || 'error',
          type: 'error',
          duration: 3 * 1000
        })
      }
      this.chuanyueDialog.attaches.push({
        name: file.name,
        path: res.data
      })
    },
    beforePicUpload(file) {
      const isPic = file.type === 'image/jpeg' || file.type === 'image/png'
      console.log('before pic upload', file.type)
      if (!isPic) this.$message.error('只能上传jpg或png格式')
      return isPic
    },
    handleRemovePic(file) {
      const fileList = this.$refs.uploadpic.uploadFiles
      console.log(fileList)
      const index = fileList.findIndex((fileItem) => {
        return fileItem.uid === file.uid
      })
      fileList.splice(index, 1)
    },
    onPageSizeChange(val) {
      this.pageCount = val
      this.getList()
    },
    onCurrentPageChange(val) {
      this.pageIndex = val
      this.getList()
    },
    // 显示添加员工界面
    showChuanyueDialog() {
      this.chuanyueDialog.visible = true
      this.chuanyueDialog.danwei = ''
      this.chuanyueDialog.wenhao = ''
      this.chuanyueDialog.biaoti = ''
      this.chuanyueDialog.shouwenDate = ''
      this.chuanyueDialog.pics = []
      this.chuanyueDialog.attaches = []
      if (this.$refs.attaches) this.$refs.attaches.uploadFiles = []
    },
    async clickApply() {
      console.log('click apply', this.chuanyueDialog)
      if (!this.chuanyueDialog.danwei) return this.$message.error('请输入收文单位')
      if (!this.chuanyueDialog.biaoti) return this.$message.error('请输入标题')
      if (!this.chuanyueDialog.shouwenDate) return this.$message.error('请选择收文日期')
      if (!this.chuanyueDialog.zhaiyao) return this.$message.error('请输入摘要')

      // if (this.chuanyueDialog.readers.length == 0) return this.$message.error('请选择分发范围')

      if (this.chuanyueDialog.auditors.length == 0) return this.$message.error('请选择审核人')
      if (this.chuanyueDialog.attaches.length == 0) return this.$message.error('请添加附件')

      const auditors = []
      for (let i = 0; i != this.chuanyueDialog.auditors.length; i++) {
        auditors.push({ uid: this.chuanyueDialog.auditors[i].uid, stepName: this.chuanyueDialog.auditors[i].stepName || this.chuanyueDialog.auditors[i].positionName })
      }

      // const readers = []
      // for (let i = 0; i != this.chuanyueDialog.readers.length; i++) {
      //   readers.push(JSON.parse(this.chuanyueDialog.readers[i][1]))
      // }

      try {
        await websock.chuanyueWenjian({
          bianhao: this.chuanyueDialog.bianhao,
          danwei: this.chuanyueDialog.danwei,
          wenhao: this.chuanyueDialog.wenhao,
          biaoti: this.chuanyueDialog.biaoti,
          shouwenDate: moment(this.chuanyueDialog.shouwenDate).format('YYYY-MM-DD'),
          zhaiyao: this.chuanyueDialog.zhaiyao,
          pics: this.chuanyueDialog.pics,
          attaches: this.chuanyueDialog.attaches || [],
          fileTag: this.chuanyueDialog.fileTag,
          // readers,
          auditors
        })

        this.$message.success('申请成功,请等待审核')

        this.chuanyueDialog.visible = false

        this.getList()
      } catch (err) {
        this.$message.error(err.message || 'error')
      }
    },
    async revertApply(idx) {
      try {
        await websock.revertChuanyueWenjian({
          id: this.list[idx].id
        })
        this.list[idx].sta = 4
        this.getList()
      } catch (err) {
        console.error(err)
        this.$message.error({
          title: err.message || 'error'
        })
      }
    },
    seeDetail(id) {
      this.detailDialog.visible = true
      this.detailDialog.id = id
    },
    printPdf(id) {
      websock.printPdf({ typ: 17, id }).then(res => {
        console.log('print pdf', res)
        const a = document.createElement('a')
        a.style.display = 'none'
        a.href = res
        a.target = '_blank'
        document.body.appendChild(a)
        a.click()
        URL.revokeObjectURL(a.href)
        document.body.removeChild(a)
      })
    }
  }
}
</script>

<style>
@import url("../../styles/form.css");
</style>
